package org.grow.share.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

/**
 * @Author: xwg
 * @CreateDate: 2021/10/11
 */

@Controller
public class UploadAbout {

    @Autowired
    private Random random;
    @Value("${repo}")
    private String repo;
    @Value("${openUpload}")
    private Boolean openUpload;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                          HttpServletRequest request) throws IOException {
        if (!openUpload){
            return "test";
        }
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件为空");
        }
        String originalFilename = file.getOriginalFilename();
        String remoteHost = request.getRemoteHost();
        System.out.println("来自 : " + remoteHost + " 的上传文件" +originalFilename);
        String[] splitHost = remoteHost.split("\\.");
        if (splitHost.length != 4) {
            throw new RuntimeException("远程地址名称不合法");
        }
        String ip = splitHost[3];
        String[] split = originalFilename.split("\\.");
        if (split.length != 2) {
            throw new RuntimeException("上传文件名称不合法");
        }
        Path repos = Paths.get(repo);
        Path f = repos.resolve(split[0] + "=" + ip + "=" + random.nextInt(1000) + "." + split[1]);

        file.transferTo(f);
        System.out.println("上传成功: "+repos);

        return "uploaded";
    }
}
